package com.fc.mall.decoration.link.rs;

import com.fc.mall.base.object.Result;
import com.fc.mall.decoration.link.model.Link;
import com.fc.mall.decoration.link.object.LinkCreate;
import com.fc.mall.decoration.link.object.LinkInfo;
import com.fc.mall.decoration.link.object.LinkUpdate;
import com.fc.mall.decoration.link.service.LinkService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@Validated
@RestController
@RequestMapping("/admin/links")
public class AdminLinkResource {
    @Autowired
    LinkService linkService;

    @Autowired
    MapperFacade mapperFacade;

    @ApiOperation("创建链接")
    @PostMapping
    public Result createPage(@Valid @RequestBody LinkCreate linkCreate) {
        Link link = linkService.createLink(linkCreate);
        LinkInfo linkInfo = mapperFacade.map(link, LinkInfo.class);
        return Result.success(linkInfo);
    }

    @ApiOperation("根据id来获取链接")
    @GetMapping("/{linkId}")
    public Result getLinkInfo(
            @ApiParam(name = "linkId", required = true, value = "LinkId") @PathVariable("linkId") String linkId) {
        Link link = linkService.getLink(linkId);
        LinkInfo linkInfo = mapperFacade.map(link, LinkInfo.class);
        return Result.success(linkInfo);
    }

    @ApiOperation("更新链接")
    @PutMapping("/{linkId}")
    public Result updateLink(@ApiParam(name = "linkId", required = true, value = "LinkId") @PathVariable("linkId") String linkId,
                             @Valid @RequestBody LinkUpdate linkUpdate) {
        Link link = linkService.updateLink(linkId, linkUpdate);
        LinkInfo linkInfo = mapperFacade.map(link, LinkInfo.class);
        return Result.success(linkInfo);
    }

    @ApiOperation("删除链接")
    @DeleteMapping("/{linkId}")
    public Result deleteLink(@ApiParam(name = "linkId", required = true, value = "LinkId") @PathVariable("linkId") String linkId) {
        linkService.deleteLink(linkId);
        return Result.success();
    }
}
